<template>
  <div class="container">
    <toast-layer v-if="toastShow" :toastContent="toastContent" :toastDesc="toastDesc" :toastType="toastType"></toast-layer>
    <div class="img-main pad-l-15 pad-r-15 pad-t-13">
      <div class="flex v-align-c img-title">
        <van-checkbox :value="mainAll.checked"
          checked-color="#ff4b24" @click="checkClick(mainAll, 1)">
          <span class="font-color-6 font-13">商品主图({{ selectMain.length }}/{{ mainImgs.length }})</span>
        </van-checkbox>
        <div class="flex-item"></div>
        <button size="mini" class="mini-btn font-12" @click="downLoad(1)">下载</button>
      </div>
      <!-- 主图开始 -->
      <div class="img-box">
        <div v-for="(item, index) in mainImgs" :key="index"
          class="img-bar" @click="checkClick(item, 2, index)">
          <van-checkbox :value="item.checked" checked-color="#ff4b24">
            <img v-if="item" class="width-99 height-99" mode="aspectFill" :src="item.src"/>
          </van-checkbox>
        </div>        
      </div>
      <p>下载速度根据您当前的实际网络速度而定，期间请勿操作耐心等待。</p>
      <!-- 主图结束 -->
      <div class="height-20"></div>
      <!-- 详情图开始 -->
      <template v-if="detailNone">
        <div class="flex v-align-c img-title">
          <van-checkbox :value="detailAll.checked"
            checked-color="#ff4b24" @click="checkClick(detailAll, 3)">
            <span class="font-color-6 font-13">商品详情图({{ selectDetail.length }}/{{ detailImgs.length }})</span>
          </van-checkbox>
          <div class="flex-item"></div>
          <button size="mini" class="mini-btn font-12" @click="downLoad(2)">下载</button>
        </div>
        <div class="img-box">
          <div v-for="(item, index) in detailImgs" :key="index"
            class="img-bar" @click="checkClick(item, 4, index)">
            <van-checkbox :value="item.checked" checked-color="#ff4b24">
              <img v-if="item" class="width-99 height-99" mode="aspectFill" :src="item.src"/>
            </van-checkbox>
          </div>        
        </div>
        <p>下载速度根据您当前的实际网络速度而定，期间请勿操作耐心等待。</p>
      </template>
      <!-- 详情图结束 -->
    </div>
    <div class="height-90"></div>
    <div class="footer-bar flex flex-center">
      <span class="font-w font-18" @click="downLoad(3)">一键下载全部</span>
    </div>
  </div>
</template>

<script>
  import ToastLayer from '@/components/ToastLayer'
  import { getGoodsDetailImgs } from '@/api/shop'

  export default {
    components: { ToastLayer },
    data() {
      return {
        mainAll: {
          checked: false
        },
        detailAll: {
          checked: false
        },
        mainImgs: [],
        selectMain: [],
        detailImgs: [],
        selectDetail: [],
        selectTotal: [],
        detailNone: false,
        downIndex: 0,
        toastShow: false,
        toastType: '',
        toastContent: '',
        toastDesc: ''
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
    },
    mounted() {
      this.toastShow = false
      this.downIndex = 0
      this.mainImgs = []
      this.selectMain = []
      this.detailImgs = []
      this.selectDetail = []
      this.selectTotal = []
      this.getGoodsDetailImgs()
    },
    methods: {
      downLoad(type) {
        let that = this
        switch (type) {
          case 1:
            if (!that.selectMain.length) return that.$utils.showToast({ title: '请选择下载图片' })
            break
          case 2:
            if (!that.selectDetail.length) return that.$utils.showToast({ title: '请选择下载图片' })
            break
          case 3:
            if (!that.selectTotal.length) return that.$utils.showToast({ title: '请选择下载图片' })
            break
        }
        if (type === 3) {
          this.selectTotal = this.selectMain.concat(this.selectDetail)
        }
        // 获取用户授权的权限
        this.$pt.getSetting({
          success: res => {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              // 如果没有授权图片保存功能,则进行授权申请操作
              that.$pt.authorize({
                scope: 'scope.writePhotosAlbum',
                success: function(opres) {
                  // 授权图片保存功能成功
                  that.$utils.showToast({ title: '下载中请勿操作' })
                  // 调用保存图片函数
                  that.drawPage(type)
                },
                fail: function(res) {
                  this.toastShow = true
                  this.toastType = 'warm'
                  this.toastContent = '下载失败，请重新发起55'
                }
              })
            } else {
              // 已经授权过图片保存功能的则，直接调用保存图片函数
              that.drawPage(type)
            }
          },
          fail: function(res) {
            this.toastShow = true
            this.toastType = 'warm'
            this.toastContent = '下载失败，请重新发起11'
          }
        })
      },
      drawPage(type) {
        let that = this
        let arrData = []
        switch (type) {
          case 1:
            arrData = that.selectMain
            break
          case 2:
            arrData = that.selectDetail
            break
          case 3:
            arrData = that.selectTotal
            break
        }
        if (this.downIndex < arrData.length) {
          this.$pt.downloadFile({
            url: arrData[that.downIndex].src + '?imageView2/1/w/700/h/700',
            success: (img) => {
              // 将图片保存到相册
              that.$pt.saveImageToPhotosAlbum({
                filePath: img.tempFilePath,
                success: (res) => {
                  that.downIndex++
                  that.toastShow = true
                  that.toastType = 'loading'
                  that.toastContent = '下载中请勿操作'
                  that.toastDesc = that.downIndex + '/' + arrData.length
                  return that.drawPage(type)
                },
                fail: function(err) {
                  that.toastShow = true
                  that.toastType = 'warm'
                  that.toastContent = '下载失败，请重新发起33'
                  console.log('fail')
                  if (err.errMsg.indexOf('cancel') !== -1) return wx.hideLoading()
                  console.log(`第${that.downIndex + 1}张保存失败`)
                  return that.drawPage(type)
                }
              })
            },
            fail: function(res) {
              this.toastShow = true
              this.toastType = 'warm'
              this.toastContent = '下载失败，请重新发起22'
            }
          })
        } else {
          this.downIndex = 0
          wx.hideLoading()
          setTimeout(() => {
            this.toastShow = true
            this.toastType = 'success'
            this.toastContent = '下载成功'
            this.toastDesc = '请查看手机相册'
          }, 800)
        }
      },
      getGoodsDetailImgs() {
        this.$utils.showToast({
          title: '加载中',
          icon: 'loading'
        })
        const goodsId = this.getCurrentPage().query.goodsId
        if (!goodsId) {
          return
        }
        getGoodsDetailImgs({
          goodsId: goodsId
        }).then((response) => {
          if (response.isError) return
          this.$pt.hideToast()
          response.data.imageList.forEach(item => {
            this.mainImgs.push({
              checked: false,
              src: item
            })
          })
          if (response.data.pictureList.length) {
            response.data.pictureList.forEach(item => {
              if (item.indexOf('.jpg') !== -1 || item.indexOf('.png') !== -1 || item.indexOf('.gif') !== -1 || item.indexOf('.bmp') !== -1) {
                this.detailImgs.push({
                  checked: false,
                  src: item
                })
              }
            })
          }
          this.totalAll()
          if (this.detailImgs.length) {
            this.detailNone = true
          } else {
            this.detailNone = false
          }
        }).catch(() => {
        })
      },
      checkClick(item, type, index) {
        // type 1，为单独块全选； type 2，为图片单选
        item.checked = !item.checked
        // 主图选择
        if (type === 2) {
          if (item.checked) {
            this.selectMain.push(item)
          } else {
            this.selectMain.forEach((itemArr, indexArr) => {
              if (itemArr.src === item.src) {
                this.selectMain.splice(indexArr, 1)
              }
            })
          }
        } else if (type === 1) {
          if (item.checked) {
            this.selectMain = []
            this.mainImgs.forEach(itemArr => {
              itemArr.checked = true
            })
            this.selectMain = this.$utils.deepClone(this.mainImgs)
          } else {
            this.selectMain = []
            this.mainImgs.forEach(itemArr => {
              itemArr.checked = false
            })
          }
        }
        // 主图是否全选
        if (this.compareArraySort(this.shortArray(this.selectMain, 'src'), this.shortArray(this.mainImgs, 'src'))) {
          this.mainAll.checked = true
        } else {
          this.mainAll.checked = false
        }
        // 详情图选择
        if (!this.detailImgs.length) return
        if (type === 4) {
          if (item.checked) {
            this.selectDetail.push(item)
          } else {
            this.selectDetail.forEach((itemArr, indexArr) => {
              if (itemArr.src === item.src) {
                this.selectDetail.splice(indexArr, 1)
              }
            })
          }
        } else if (type === 3) {
          if (item.checked) {
            this.selectDetail = []
            this.detailImgs.forEach(itemArr => {
              itemArr.checked = true
            })
            this.selectDetail = this.$utils.deepClone(this.detailImgs)
          } else {
            this.selectDetail = []
            this.detailImgs.forEach(itemArr => {
              itemArr.checked = false
            })
          }
        }
        // 详情图是否全选
        if (this.compareArraySort(this.shortArray(this.selectDetail, 'src'), this.shortArray(this.detailImgs, 'src'))) {
          this.detailAll.checked = true
        } else {
          this.detailAll.checked = false
        }
      },
      // 数组整理成一维
      shortArray(arr, key) {
        let dataArr = []
        arr.forEach(item => {
          dataArr.push(item[key])
        })
        return dataArr
      },
      // 判断两个数组相等
      compareArraySort(a1, a2) {
        if ((!a1 && a2) || (a1 && !a2)) return false
        if (a1.length !== a2.length) return false
        a1 = [].concat(a1)
        a2 = [].concat(a2)
        a1 = a1.sort()
        a2 = a2.sort()
        for (var i = 0, n = a1.length; i < n; i++) {
          if (a1[i] !== a2[i]) return false
        }
        return true
      },
      totalAll() {
        this.selectTotal = this.mainImgs.concat(this.detailImgs)
        this.mainAll.checked = true
        this.detailAll.checked = true
        this.mainImgs.forEach(itemArr => {
          itemArr.checked = true
        })
        this.selectMain = this.$utils.deepClone(this.mainImgs)
        this.detailImgs.forEach(itemArr => {
          itemArr.checked = true
        })
        this.selectDetail = this.$utils.deepClone(this.detailImgs)
      }
    }
  }
</script>

<style lang="less" scoped>
.container{
  background: #ffffff;
  min-height: 100vh;
  border-top: #e7e7e7 1px solid;
  .img-main{
    p{
      font-size: 11px;
      color: #999999;
      padding-left: 10px;
      padding-top: 2px;
    }
  }
  .img-title{
    .mini-btn{
      background-color: #fff;
      border: #333 1px solid;
      border-radius: 3px;
      color: #333;
      padding: 3px 7px;
      line-height: 1;
    }
    margin-bottom: 10px;
  }
  .img-box{
    background: #f7f5f6;
    border-radius: 8px;
    padding: 12px 12px 0 12px;
    .img-bar{
      display: inline-block;
      vertical-align: top;
      width: 33.3%;
      text-align: center;
      margin-bottom: 12px;
    }
    &:after{
      content: '';
      display: block;
      clear: both;
    }
    /deep/ ._van-checkbox{
      justify-content: center;
      align-items: center;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
    }
    /deep/ .van-checkbox{
      position: relative;
      .van-checkbox__icon-wrap{
        position: absolute;
        right: 6px;
        top: 6px;
      }
      .van-checkbox__icon{
        border-color: #D5D5D5;
        background-color: #ffffff;
      }
      .van-checkbox__label{
        margin-left: 0;
      }
    }
  }
  .footer-bar{
    position: fixed;
    left: 0;
    bottom: 0;
    background: #fff;
    width: 100%;
    height: 80px;
    text-align: center;
    span{
      display: inline-block;
      border-radius: 100px;
      color: #fff;
      height: 45px;
      line-height: 45px;
      padding: 0 65px;
      background: linear-gradient(to right, #ff8441, #fd4f21);
    }
  }
}
</style>
